package notes

import (
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
	"tao-admin/configs"
	"tao-admin/internal/model"
)

type NoteManager struct {
}

type SearchNoteCondition struct {
	Id         *int64  `json:"id"`
	Title      *string `json:"title"`
	Body       *string `json:"body"`
	CategoryId *string `json:"category_id"`
	UserId     *string `json:"user_id"`
	Ctime      *int64  `json:"ctime"`
	Mtime      *int64  `json:"mtime"`
}

func (manager *NoteManager) SearchNoteByCondition(ctx *gin.Context, condition *SearchNoteCondition) ([]model.NoteTab, int64, error) {
	page, _ := strconv.Atoi(ctx.Query("page"))
	count, _ := strconv.Atoi(ctx.Query("perPage"))

	db := configs.GetGormDB()
	list := make([]model.NoteTab, 0)
	var total int64 = 0

	if condition.Id != nil {
		db = db.Where("id=?", condition.Id)
	}
	if condition.Title != nil {
		db = db.Where("title=?", condition.Title)
	}
	if condition.Body != nil {
		db = db.Where("body=?", condition.Body)
	}
	if condition.CategoryId != nil {
		db = db.Where("category_id=?", condition.CategoryId)
	}
	if condition.UserId != nil {
		db = db.Where("user_id=?", condition.UserId)
	}
	if condition.Ctime != nil {
		db = db.Where("ctime=?", condition.Ctime)
	}
	if condition.Mtime != nil {
		db = db.Where("mtime=?", condition.Mtime)
	}

	err1 := db.Model(&model.NoteTab{}).Count(&total).Error
	if page > 0 && count > 0 {
		db = db.Limit(count).Offset((page - 1) * count)
	}

	db = db.Order("id DESC, mtime DESC")

	err2 := db.Find(&list).Error
	if err1 != nil || err2 != nil {
		return nil, 0, nil
	}

	log.Printf("查表结束, list: %v", list)
	return list, total, nil
}

func (manager *NoteManager) CreateNoteMng(ctx *gin.Context, item model.NoteTab) error {
	db := configs.GetGormDB()
	err := db.Create(&item).Error
	if err != nil {
		return err
	}
	return nil
}

func (manager *NoteManager) UpdateNoteMng(ctx *gin.Context, item model.NoteTab) error {
	db := configs.GetGormDB()
	updateData := model.NoteTab{
		Id:         item.Id,
		Title:      item.Title,
		Body:       item.Body,
		CategoryId: item.CategoryId,
		UserId:     item.UserId,
		Ctime:      item.Ctime,
		Mtime:      item.Mtime,
	}

	id := item.Id
	// 查询记录
	if err := db.Where("id = ?", id).First(&item).Error; err != nil {
		return err
	}

	err := db.Model(&item).Where("id = ?", id).Update(updateData).Error
	if err != nil {
		return err
	}
	return nil
}

func (manager *NoteManager) DeleteNoteMng(ctx *gin.Context, item model.NoteTab) error {
	db := configs.GetGormDB()
	id := item.Id
	// 查询记录
	if err := db.Where("id = ?", id).First(&item).Error; err != nil {
		return err
	}
	err := db.Delete(&item).Error
	if err != nil {
		return err
	}
	return nil
}
